package com.ydd.service.impl;

import com.ydd.context.BaseContext;
import com.ydd.entity.*;
import com.ydd.info.*;
import com.ydd.mapper.*;
import com.ydd.service.IConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ydd.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hgz
 * @since 2023-05-30
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService {
    @Autowired
    private ConfigMapper configMapper;
    @Autowired
    private CateMapper cateMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private YddUserMapper yddUserMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdvimgMapper advimgMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private LinkMapper linkMapper;

    /**
     * 获取系统配置
     *
     * @return
     */
    @Override
    public ConfigVO getConfig() {
        //List<Map<String, String>> mapList = configMapper.getConfig(ConfigConstant.SYSTEM);
        //for (Map<String, String> map : mapList) {
        //
        //}
        String login_title = configMapper.getConfig("login_title");
        String login_bg = configMapper.getConfig("login_bg");
        String system_name = configMapper.getConfig("system_name");
        String system_log = configMapper.getConfig("system_logo");
        String web_ico = configMapper.getConfig("web_ico");

        return ConfigVO.builder()
                .login_title(login_title)
                .login_bg(login_bg)
                .system_name(system_name)
                .system_log(system_log)
                .web_ico(web_ico)
                .build();
    }

    /**
     * 主页信息统计
     *
     * @return
     */
    @Override
    public BaseInfoVO baseInfo() {
        String adminId = roleMapper.getAdminId();
        Integer admin_num = sysUserMapper.getCountAdmin(adminId);
        Integer advimg_num = advimgMapper.getCount();
        List<Cate> cateList = cateMapper.all();
        List<CateBaseInfoVO> all_cate = new ArrayList<>();
        cateList.forEach(cate -> {
            CateBaseInfoVO cateBaseInfoVO = new CateBaseInfoVO();
            BeanUtils.copyProperties(cate, cateBaseInfoVO);
            cateBaseInfoVO.setNum(cate.getSortNum());
            all_cate.add(cateBaseInfoVO);
        });

        Integer article_num = articleMapper.getCount();
        Integer cate_num = cateMapper.getCount();

        List<Article> articleList = articleMapper.getHotArticle();
        List<ArticleBaseInfoVO> hot_article = new ArrayList<>();
        articleList.forEach(article -> {
            ArticleBaseInfoVO articleBaseInfoVO = new ArticleBaseInfoVO();
            BeanUtils.copyProperties(article, articleBaseInfoVO);
            hot_article.add(articleBaseInfoVO);
        });

        List<YddUser> userList = yddUserMapper.getNewUserNum();
        List<NewUserVO> new_user = new ArrayList<>();
        userList.forEach(yddUser -> {
            NewUserVO newUserVO = new NewUserVO();
            BeanUtils.copyProperties(yddUser, newUserVO);
            new_user.add(newUserVO);
        });

        Integer tag_num = tagMapper.getCount();
        Integer total = yddUserMapper.getTotal(null);
        Integer user_man = yddUserMapper.getTotal(0);
        Integer user_woman = yddUserMapper.getTotal(1);
        UserTotle userTotle = UserTotle.builder().total(total).user_man(user_man).user_woman(user_woman).build();
        return BaseInfoVO.builder()
                .admin_num(admin_num)
                .advimg_num(advimg_num)
                .all_cate(all_cate)
                .article_num(article_num)
                .cate_num(cate_num)
                .hot_article(hot_article)
                .new_user(new_user)
                .tag_num(tag_num)
                .user(userTotle)
                .build();
    }

    /**
     * 获取用户资料
     *
     * @return
     */
    @Override
    public UserProfileVO getUserProfile() {
        String userId = BaseContext.getCurrentId();
        //根据id查询sys_user表信息
        SysUser sysUser = sysUserMapper.findById(userId);

        String roleId = sysUser.getRoleId().replace("[", "")
                .replace("]", "").replace("\"", "");
       // String[] roleIdList = userRoleIds.split(",");

        //创建UserInfo对象
        UserInfo userInfo = new UserInfo();
        //把sysUser数据赋值给userInfo
        BeanUtils.copyProperties(sysUser, userInfo);
        userInfo.setLogin_name(sysUser.getLoginName());
        userInfo.setLogin_ip(sysUser.getLoginIp());
        userInfo.setLogin_date(sysUser.getLoginDate());
        userInfo.setCreate_date(sysUser.getCreateDate());
        userInfo.setUpdate_date(sysUser.getUpdateDate());
        userInfo.setRole_id(roleId);
        userInfo.setDefault_data(sysUser.getDefaultData());
        //查询角色名称
        String name = roleMapper.findNameById(userInfo.getRole_id());
        //创建角色名称列表
        List<String> rolename = new ArrayList<>();
        rolename.add(name);

        List<Integer> menuIdList = roleMenuMapper.findMenuIdByRoleId(userInfo.getRole_id());
        if(menuIdList == null){
            throw new RuntimeException();
        }

        //创建用户菜单权限列表
        List<Menu>  menuList = menuMapper.findByIds(menuIdList);

        //查询字典表信息
        List<String> allType = dictMapper.findAllType();
        Map<String, Map<String,String>> dictMap = new HashMap<>();
        allType.forEach(type ->{
            List<String> valueList = dictMapper.findByCondition(type);
            valueList.stream().forEach(value ->{
                        Map<String, String> valueMap = new HashMap<>();
                        valueMap.put(value, value);
                        dictMap.put(type, valueMap);
                    });
        });

        //创建字典列表
        Map<String, Map<String, Map<String,String>>> dictsList = new HashMap<>();
        dictsList.put("dictList", dictMap);

        //创建用户按钮权限列表
        List<String> btnList = new ArrayList<>();
        btnList.add("*");

        return UserProfileVO.builder()
                .rolename(rolename)
                .userInfo(userInfo)
                .menuList(menuList)
                .dictsList(dictsList)
                .btnList(btnList)
                .build();
    }

    /**
     * 首页和全局配置
     * @return
     */
    @Override
    public IndexResult index() {
        //获取所有分类数据
        List<Cate> cateList = cateMapper.all();
        List<CateInfo> allCate = new ArrayList<>();
        cateList.forEach(cate -> {
            CateInfo cateInfo = new CateInfo();
            BeanUtils.copyProperties(cate, cateInfo);
            cateInfo.setSort_num(cate.getSortNum());
            cateInfo.setDefault_data(cate.getDefaultData());
            allCate.add(cateInfo);
        });

        //获取所有链接
        List<Link> linkList = linkMapper.all();
        List<LinkInfo> allLink = new ArrayList<>();
        linkList.forEach(link -> {
            LinkInfo linkInfo = new LinkInfo();
            BeanUtils.copyProperties(link, linkInfo);
            linkInfo.setDefault_data(link.getDefaultData());
            allLink.add(linkInfo);
        });

        //获取所有标签
        List<Tag> tagList = tagMapper.all();
        List<TagInfo> allTag = new ArrayList<>();
        tagList.forEach(tag -> {
            TagInfo tagInfo = new TagInfo();
            BeanUtils.copyProperties(tag, tagInfo);
            tagInfo.setDefault_data(tag.getDefaultData());
            allTag.add(tagInfo);
        });

        //获取轮播图数据
        List<Advimg> bannerList = advimgMapper.findByAdvposId(15);
        List<AdvimgInfo> banner = new ArrayList<>();
        bannerList.forEach(advimg -> {
            AdvimgInfo advimgInfo = new AdvimgInfo();
            BeanUtils.copyProperties(advimg, advimgInfo);
            banner.add(advimgInfo);
        });

        //获取侧边栏图片
        List<Advimg> sideBannerList = advimgMapper.findByAdvposId(14);
        List<AdvimgInfo> sideBanner = new ArrayList<>();
        sideBannerList.forEach(advimg -> {
            AdvimgInfo advimgInfo = new AdvimgInfo();
            BeanUtils.copyProperties(advimg, advimgInfo);
            sideBanner.add(advimgInfo);
        });

        //获取详情广告图
        List<Advimg> showBannerList = advimgMapper.findByAdvposId(13);
        List<AdvimgInfo> showBanner = new ArrayList<>();
        showBannerList.forEach(advimg -> {
            AdvimgInfo advimgInfo = new AdvimgInfo();
            BeanUtils.copyProperties(advimg, advimgInfo);
            showBanner.add(advimgInfo);
        });

        //获取所有配置信息
        List<ConfigInfo> allData = new ArrayList<>();
        List<Config> configList = configMapper.selectList(null);
        configList.forEach(config -> {
            ConfigInfo configInfo = new ConfigInfo();
            BeanUtils.copyProperties(config, configInfo);
            configInfo.setAttr_key(config.getAttrKey());
            configInfo.setAttr_value(config.getAttrValue());
            configInfo.setConfig_value(config.getConfigValue());
            allData.add(configInfo);
        });

        List list = new ArrayList();
        //查询配置列表
        List<String> keyList = configMapper.findKeyList();
        Map<String, Object> keyMap1 = new HashMap<>();
        Map<String, Object> keyMap2 = new HashMap<>();
        Map<String, Object> keyMap3 = new HashMap<>();
        keyList.forEach(key ->{
            if ("base".equals(key)){
                keyMap1.put("name", "基础配置");
                keyMap1.put("key", key);
                List children = new ArrayList();
                //查询子配置列表
                List<String> valueList = configMapper.findByKey(key);

                valueList.forEach(value -> {
                    Map<String, Object> valueMap = new HashMap<>();
                    List<SysConfig> date = configMapper.findByValue(value);
                    valueMap.put("name", value);
                    valueMap.put("data", date);
                    children.add(valueMap);
                });
                keyMap1.put("children",children);
            }

            if ("system".equals(key)){
                keyMap2.put("name", "系统配置");
                keyMap2.put("key", key);
                //查询子配置列表
                List<String> valueList = configMapper.findByKey(key);
                List children = new ArrayList();
                valueList.forEach(value -> {
                    Map<String, Object> valueMap = new HashMap<>();
                    List<SysConfig> date = configMapper.findByValue(value);
                    valueMap.put("name", value);
                    valueMap.put("data", date);
                    children.add(valueMap);
                });
                keyMap2.put("children",children);
            }

            if ("custom".equals(key)){
                keyMap3.put("name", "其他配置");
                keyMap3.put("key", key);
                //查询子配置列表
                List<String> valueList = configMapper.findByKey(key);
                List children = new ArrayList();
                valueList.forEach(value -> {
                    Map<String, Object> valueMap = new HashMap<>();
                    List<SysConfig> date = configMapper.findByValue(value);
                    valueMap.put("name", value);
                    valueMap.put("data", date);
                    children.add(valueMap);
                });
                keyMap3.put("children",children);
            }
        });

        list.add(keyMap1);
        list.add(keyMap2);
        list.add(keyMap3);

        //封装配置数据
        AllConfigInfo config = AllConfigInfo.builder()
                .allData(allData)
                .list(list)
                .build();

        return IndexResult.builder()
                .allCate(allCate)
                .allLink(allLink)
                .allTag(allTag)
                .config(config)
                .build();
    }
}
